import React, { useState } from 'react';
import { Card, Tabs, Table, DatePicker, Select, Button, Input, Row, Col } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { Area, Bar, Column, Line, Pie } from '@ant-design/plots';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ActivityAnalysis = () => {
  const [dateRange, setDateRange] = useState(null);
  const [activityType, setActivityType] = useState('all');
  const [searchText, setSearchText] = useState('');
  const [currentTab, setCurrentTab] = useState('overview');

  // 模拟活动数据
  const [activities, setActivities] = useState([
    {
      id: '1',
      name: '春季优惠券活动',
      type: 'coupon',
      startTime: '2024-03-01 00:00:00',
      endTime: '2024-03-31 23:59:59',
      status: 'ended',
      views: 12500,
      participants: 3250,
      conversions: 1850,
      totalAmount: 125000,
      couponValue: 50,
    },
    {
      id: '2',
      name: '会员折扣卡促销',
      type: 'discount_card',
      startTime: '2024-04-01 00:00:00',
      endTime: '2024-04-30 23:59:59',
      status: 'active',
      views: 8900,
      participants: 2150,
      conversions: 1350,
      totalAmount: 98000,
      discountRate: 0.85,
    },
    {
      id: '3',
      name: '满减活动',
      type: 'threshold_promotion',
      startTime: '2024-04-10 00:00:00',
      endTime: '2024-04-20 23:59:59',
      status: 'active',
      views: 6200,
      participants: 1850,
      conversions: 1120,
      totalAmount: 85000,
      threshold: 200,
      discount: 50,
    },
    {
      id: '4',
      name: '夏季套餐卡',
      type: 'package_card',
      startTime: '2024-05-01 00:00:00',
      endTime: '2024-05-31 23:59:59',
      status: 'upcoming',
      views: 3500,
      participants: 0,
      conversions: 0,
      totalAmount: 0,
      packagePrice: 199,
    },
  ]);

  // 销售趋势数据
  const salesTrendData = [
    { date: '2024-04-01', sales: 12000, participants: 350 },
    { date: '2024-04-02', sales: 15000, participants: 420 },
    { date: '2024-04-03', sales: 18000, participants: 480 },
    { date: '2024-04-04', sales: 16000, participants: 450 },
    { date: '2024-04-05', sales: 22000, participants: 580 },
    { date: '2024-04-06', sales: 25000, participants: 650 },
    { date: '2024-04-07', sales: 28000, participants: 720 },
    { date: '2024-04-08', sales: 32000, participants: 850 },
    { date: '2024-04-09', sales: 30000, participants: 800 },
    { date: '2024-04-10', sales: 26000, participants: 680 },
    { date: '2024-04-11', sales: 24000, participants: 650 },
    { date: '2024-04-12', sales: 29000, participants: 780 },
  ];

  // 活动类型分布数据
  const activityTypeData = [
    { type: '优惠券', value: 35 },
    { type: '折扣卡', value: 25 },
    { type: '满减活动', value: 20 },
    { type: '次数卡', value: 10 },
    { type: 'M选N卡', value: 5 },
    { type: '套餐卡', value: 5 },
  ];

  // 活动效果对比数据
  const activityComparisonData = [
    { name: '春季优惠券', views: 12500, conversions: 1850, conversionRate: 0.148 },
    { name: '会员折扣卡', views: 8900, conversions: 1350, conversionRate: 0.152 },
    { name: '满减活动', views: 6200, conversions: 1120, conversionRate: 0.181 },
    { name: '夏季套餐卡', views: 3500, conversions: 0, conversionRate: 0 },
  ];

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: '活动类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => {
        const typeMap = {
          'coupon': '优惠券',
          'discount_card': '折扣卡',
          'threshold_promotion': '满减活动',
          'count_card': '次数卡',
          'm_choose_n_card': 'M选N卡',
          'package_card': '套餐卡',
        };
        return typeMap[type] || type;
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          'upcoming': '即将开始',
          'active': '进行中',
          'ended': '已结束',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
    },
    {
      title: '参与人数',
      dataIndex: 'participants',
      key: 'participants',
    },
    {
      title: '转化人数',
      dataIndex: 'conversions',
      key: 'conversions',
    },
    {
      title: '转化金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${amount.toLocaleString()}`,
    },
  ];

  // 过滤活动数据
  const filteredActivities = activities.filter((activity) => {
    const matchesSearch = activity.name.toLowerCase().includes(searchText.toLowerCase());
    const matchesType = activityType === 'all' || activity.type === activityType;
    // 这里可以添加日期范围过滤逻辑
    return matchesSearch && matchesType;
  });

  // 销售趋势图配置
  const salesTrendConfig = {
    data: salesTrendData,
    xField: 'date',
    yField: 'sales',
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
    yAxis: {
      label: {
        formatter: (v) => `¥${v}`,
      },
    },
    legend: {
      position: 'top',
    },
  };

  // 活动类型分布图配置
  const activityTypeConfig = {
    data: activityTypeData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'inner',
      offset: '-30%',
      content: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
      style: {
        fontSize: 14,
        textAlign: 'center',
      },
    },
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
    ],
  };

  // 活动效果对比图配置
  const activityComparisonConfig = {
    data: activityComparisonData,
    xField: 'name',
    yField: 'conversionRate',
    label: {
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
      formatter: (v) => `${(v * 100).toFixed(1)}%`,
    },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    meta: {
      conversionRate: {
        alias: '转化率',
        formatter: (v) => `${(v * 100).toFixed(1)}%`,
      },
    },
  };

  // 刷新数据
  const handleRefresh = () => {
    // 这里应该调用API刷新数据，这里简化处理
    console.log('刷新数据');
  };

  // 导出数据
  const handleExport = () => {
    // 这里应该调用API导出数据，这里简化处理
    console.log('导出数据');
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>活动数据分析</h2>
        <p style={{ color: '#8c8c8c' }}>分析营销活动的效果和数据统计</p>
      </div>

      <Card
        bordered={false}
        style={{ borderRadius: 8, marginBottom: 24 }}
        extra={
          <Button type="primary" onClick={handleExport}>
            导出报表
          </Button>
        }
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 24 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <RangePicker
              style={{ width: 300 }}
              onChange={(dates) => setDateRange(dates)}
            />
            <Select
              placeholder="活动类型"
              style={{ width: 150 }}
              value={activityType}
              onChange={setActivityType}
            >
              <Option value="all">全部类型</Option>
              <Option value="coupon">优惠券</Option>
              <Option value="discount_card">折扣卡</Option>
              <Option value="threshold_promotion">满减活动</Option>
              <Option value="count_card">次数卡</Option>
              <Option value="m_choose_n_card">M选N卡</Option>
              <Option value="package_card">套餐卡</Option>
            </Select>
            <Input
              placeholder="搜索活动名称"
              style={{ width: 200 }}
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
        </div>

        <Tabs
          activeKey={currentTab}
          onChange={setCurrentTab}
          style={{ marginBottom: 24 }}
        >
          <Tabs.TabPane key="overview" tab="概览">
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Card
                  bordered={false}
                  style={{ borderRadius: 8, backgroundColor: '#f0f9ff' }}
                >
                  <div style={{ textAlign: 'center', padding: 24 }}>
                    <h3 style={{ marginBottom: 12, color: '#1890ff' }}>总浏览量</h3>
                    <p style={{ fontSize: 28, fontWeight: 'bold', marginBottom: 4 }}>31,100</p>
                    <p style={{ color: '#8c8c8c' }}>较上月增长 12.5%</p>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card
                  bordered={false}
                  style={{ borderRadius: 8, backgroundColor: '#f6ffed' }}
                >
                  <div style={{ textAlign: 'center', padding: 24 }}>
                    <h3 style={{ marginBottom: 12, color: '#52c41a' }}>参与人数</h3>
                    <p style={{ fontSize: 28, fontWeight: 'bold', marginBottom: 4 }}>7,250</p>
                    <p style={{ color: '#8c8c8c' }}>较上月增长 8.3%</p>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card
                  bordered={false}
                  style={{ borderRadius: 8, backgroundColor: '#fff7e6' }}
                >
                  <div style={{ textAlign: 'center', padding: 24 }}>
                    <h3 style={{ marginBottom: 12, color: '#faad14' }}>转化金额</h3>
                    <p style={{ fontSize: 28, fontWeight: 'bold', marginBottom: 4 }}>¥308,000</p>
                    <p style={{ color: '#8c8c8c' }}>较上月增长 15.2%</p>
                  </div>
                </Card>
              </Col>
            </Row>

            <div style={{ marginTop: 24 }}>
              <h3 style={{ marginBottom: 16 }}>销售趋势</h3>
              <Card bordered={false} style={{ borderRadius: 8 }}>
                <div style={{ height: 400 }}>
                  <Area {...salesTrendConfig} />
                </div>
              </Card>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane key="typeAnalysis" tab="类型分析">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Card bordered={false} style={{ borderRadius: 8, height: '100%' }}>
                  <h3 style={{ marginBottom: 16 }}>活动类型分布</h3>
                  <div style={{ height: 300 }}>
                    <Pie {...activityTypeConfig} />
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card bordered={false} style={{ borderRadius: 8, height: '100%' }}>
                  <h3 style={{ marginBottom: 16 }}>活动效果对比</h3>
                  <div style={{ height: 300 }}>
                    <Bar {...activityComparisonConfig} />
                  </div>
                </Card>
              </Col>
            </Row>
          </Tabs.TabPane>
          <Tabs.TabPane key="detail" tab="活动详情">
            <Table
              columns={columns}
              dataSource={filteredActivities}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              rowKey="id"
            />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default ActivityAnalysis;